package org.shoukaiseki.common.utils;


import java.math.BigDecimal;
import java.util.Arrays;

/**
 * 62进制转换
 */
public class Base62Decimal {

    //顺序按照ASCII,否则 62转10进制是会出错
    private  final static char[] digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".toCharArray();

    /**
     static final char[] digits = {
     '0' , '1' , '2' , '3' , '4' , '5' ,
     '6' , '7' , '8' , '9' , 'a' , 'b' ,
     'c' , 'd' , 'e' , 'f' , 'g' , 'h' ,
     'i' , 'j' , 'k' , 'l' , 'm' , 'n' ,
     'o' , 'p' , 'q' , 'r' , 's' , 't' ,
     'u' , 'v' , 'w' , 'x' , 'y' , 'z' ,
     'A' , 'B' , 'C' , 'D' , 'E' , 'F' ,
     'G' , 'H' , 'I' , 'J' , 'K' , 'L' ,
     'M' , 'N' , 'O' , 'P' , 'Q' , 'R' ,
     'S' , 'T' , 'U' , 'V' , 'W' , 'X' ,
     'Y' , 'Z' , '-' , '_' ,
     };
     */

    private  final static int radix = digits.length;

    public static String convertDecimalToBase62ToString(long val){

        byte[] bytes = convertDecimalToBase62(val);
        if(bytes.length==0){
            return "0";
        }else {
            return new String(bytes).trim();
        }

    }

    /**
     * 十进制转62进制
     * @param val
     * @return
     */
    public static byte[] convertDecimalToBase62(long val){
        if(val==0){
            return new byte[0];
        }

        int mag = Long.SIZE - Long.numberOfLeadingZeros(val);
        int chars = Math.max(((mag + (5 - 1)) / 5), 1);
        byte[] buf = new byte[chars];

        long valTemp=val;
        do {
            int remainder = (int) (valTemp % radix);
            buf[--chars]=(byte)digits[remainder];
            valTemp=valTemp/radix;
        }while (chars>0&&valTemp>0);

        return buf;
    }


    public static long convertBase62ToDecimal(String str){
        return convertBase62ToDecimal(str.getBytes());
    }

    /**
     * 62进制转10进制
     * @param bytes
     * @return
     */
    public static long convertBase62ToDecimal(byte[] bytes){
        long val=0;

        int j=0;
        for (int i = bytes.length-1; i >= 0; i--) {

            long pow = BigDecimal.valueOf(Math.pow(radix, j++)).longValue();
            int intTemp = Arrays.binarySearch(digits, (char) bytes[i]);
//            System.out.println("intTemp="+intTemp);
            val+= pow *intTemp;
//            System.out.println("pow="+val);
//            System.out.println("val="+val);
//            System.out.println(bytes[i]);
        }

        return val;
    }

}


